function [summd5] = md5sum(varargin)
% md5sum  - calculate the MD5 sum over a file or a stream
%
% FORMAT:       summd5 = md5sum(fileorvar [,isavar])
%
% Input fields:
%
%       fileorvar   either a filename or any variable that can
%                   be used for an exact any2ascii conversion
%       isavar      in case a possibly valid filename is given
%                   but the md5sum over the name rather than the
%                   contents of the file is requested
%
% Output fields:
%
%       summd5      an 1x32 char array with the lower case md5sum
%
% NOTE:         md5sum makes use of an external binary in _bin
%               (for MS Windows) or the GNU util (must be on the
%               PATH). hence it must write a file to disk (for
%               which tempname is used).
%
% See also any2ascii, hxdouble.

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% argument check
if nargin < 1
    error( ...
        'BVQXtools:TooFewArguments', ...
        'Too few arguments. Try ''help %s''.', ...
        mfilename ...
    );
end
fileorstream = varargin{1};

% persistent binary location
persistent md5sum_binloc;
if isempty(md5sum_binloc)

    % get path of current mfile
    md5sum_binloc = bvqxtools_path('bin');
    if ispc
        md5sum_binloc = ['"' strrep(md5sum_binloc, '/', '\') '\md5sum.exe"'];
    else
        md5sum_binloc = invsystem('which md5sum');
        if isempty(md5sum_binloc)
            md5sum_binloc = invsystem('which md5');
        end
        if any(md5sum_binloc == ' ' | md5sum_binloc == ':')
            error( ...
                'BVQXtools:MissingBinary', ...
                'Couldn''t reliably detect md5sum binary.' ...
            );
        end
    end
end

% default error
summd5 = 'ERROR_BUILDING_MD5SUM';

% file
if nargin == 1 && ...
    ischar(fileorstream) &&  ...
    numel(fileorstream) == size(fileorstream, 2) && ...
    numel(fileorstream) < 1000 && ...
    exist(fileorstream, 'file') == 2

    % set testfilename to ''
    tfname = '';

% stream
else

    % non-1D-char arrays
    if ~ischar(fileorstream) || ...
        numel(fileorstream) ~= length(fileorstream)

        % convert first
        fileorstream = any2ascii(fileorstream, 'exact');

    % else linearize
    else
        fileorstream = fileorstream(:)';
    end

    % create temp name
    tfname = sprintf('%s_%08d', tempname, floor(rand(1, 1) * 2^24));

    % write to tempname
    asciiwrite(tfname, fileorstream);

    % set stream to filename
    fileorstream = tfname;
end

% check file
if ispc
    [iresult,istatus] = invsystem([md5sum_binloc ' "' fileorstream '"']);
else
    [iresult,istatus] = invsystem([md5sum_binloc ' ' fileorstream]);
end

% delete empty file if any
if ~isempty(tfname)
    try
        delete(tfname);
    catch
        % nothing
    end
end

% return on bad status
if istatus
    return;
end

% otherwise try to extract MD5
md5pos = regexpi(iresult,'([0-9a-f]{32})');
if ~isempty(md5pos)
    summd5 = iresult(md5pos(1):md5pos(1)+31);
end
